package org.example.workqueue;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;
import com.rabbitmq.client.Delivery;

import java.io.IOException;

public class WorkQueueConsumer2Test {

    private static final String QUEUE_NAME = "work_queue";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        boolean autoAck = false;
        //非公平分发
        channel.basicQos(10);
        channel.basicConsume(QUEUE_NAME, autoAck, new DeliverCallback() {
                    int count = 0;

                    @Override
                    public void handle(String consumerTag, Delivery message) throws IOException {
                        System.out.println("C2收到消息=" + new String(message.getBody()));
                        try {
                            Thread.sleep(10000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        count++;
                        //关闭自动确认，需要手动确认下
                        channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
                        System.out.println("消息第" + count);

                    }
                }, (consumerTag) ->
                        System.out.println("C2消费失败,tag=" + consumerTag)
        );
    }
}
